#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author  : Lee
# @File    : dhy_cut_trajectory_view.py
# @Time    : 2024/1/22 16:31
import os
import csv
import numpy as np
from PyQt5 import QtCore, QtWidgets
from PyQt5.QtWidgets import QWidget, QMessageBox
from util.common_calc import get_distance_of_two_point
from views.alert_messagebox_view import show_message_box
from views.dhy_connect_row_matplotlib_view import ConnectRowMplWidget
from views.resource_view.cut_trajectory_points_view import Ui_DHYCutTrajectoryPointsView


class DHYCutTrajectoryView(QWidget, Ui_DHYCutTrajectoryPointsView):
    def __init__(self, parent=None):
        super(DHYCutTrajectoryView, self).__init__(parent)
        self.setupUi(self)

        # 添加matplotlib视图
        matplotlib_widget = ConnectRowMplWidget(self)
        self.matplotlib_layout.addWidget(matplotlib_widget)
        self.matplotlib_view = matplotlib_widget.qCanvas

        self.csv_file_path = ""
        self.matplotlib_view_points = None
        self.left_index, self.right_index = 0, -1
        self.load_data_btn.clicked.connect(self.select_csv_file)
        self.export_data_btn.clicked.connect(self.export_csv_file)

    @QtCore.pyqtSlot()
    def select_csv_file(self):
        options = QtWidgets.QFileDialog.Options()
        options |= QtWidgets.QFileDialog.DontUseNativeDialog
        self.csv_file_path, _ = QtWidgets.QFileDialog.getOpenFileName(None, "QFileDialog.getOpenFileName()", "",
                                                                      "CSV Files (*.csv)", options=options)
        self.load_trajectory_points_data()

    @QtCore.pyqtSlot()
    def export_csv_file(self):
        if not self.csv_file_path:
            QMessageBox.warning(self, "警告", "请先加载轨迹数据文件！")
            return
        # 创建一个对话框让用户选择导出路径
        directory = QtWidgets.QFileDialog. \
            getExistingDirectory(None, "选择导出目录", "",
                                 QtWidgets.QFileDialog.ShowDirsOnly | QtWidgets.QFileDialog.DontResolveSymlinks)
        if directory:
            _data = np.loadtxt(self.csv_file_path, delimiter=',')
            with open(os.path.join(directory, "cut_" + os.path.basename(self.csv_file_path)), 'w',
                      encoding='utf-8', newline='') as f_obj:
                writer = csv.writer(f_obj)
                writer.writerows(_data[min(self.left_index, self.right_index):max(self.left_index, self.right_index) + 1])
                self.close()

    def load_trajectory_points_data(self):
        self.matplotlib_view_points = self.matplotlib_view.load_data_with_csv_file_path(self.csv_file_path)

    def get_clicked_index(self, clicked_indexes):

        _title = "设置左、右截断线"
        _text = "左右截断线全部设置后，将截取两条截断线之前的轨迹点参与衔接行精度计算"
        _btn_text_list = ["左截断线", "右截断线", "取消"]
        clicked_btn = show_message_box(_title, _text, _btn_text_list)

        if "截断线" in clicked_btn:
            point = list()
            # 设置成左截断线时，多个轨迹点去最后一个，设置成右截断线时，多个轨迹点取第一个
            if clicked_btn == "左截断线":
                self.left_index = clicked_indexes[-1]
                point = self.matplotlib_view_points[self.left_index]
            else:
                self.right_index = clicked_indexes[0]
                point = self.matplotlib_view_points[self.right_index]
            matplotlib_view_y_values = self.matplotlib_view.draw_point.get_ydata()
            _y_max = max(matplotlib_view_y_values)
            _y_min = min(matplotlib_view_y_values)
            _x_points = [point[0], point[0]]
            _y_points = [_y_max, _y_min]
            self.matplotlib_view.update_line([_x_points, _y_points],
                                             "left_line" if clicked_btn == "左截断线" else "right_line")

        _point_left = self.matplotlib_view_points[max(self.left_index, 0)]
        _point_right = self.matplotlib_view_points[max(self.right_index, -1)]
        _dis = get_distance_of_two_point(_point_left, _point_right)
        self.trajectory_dis_text.setText(str(round(_dis, 2)))
